    #!/usr/bin/env python3
# -*- coding: utf-8 -*-

import http.server
import socketserver
import os
import sys
from urllib.parse import urlparse

class CustomHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory="front_end_pc", **kwargs)
    
    def do_GET(self):
        # 解析URL
        parsed_path = urlparse(self.path)
        path = parsed_path.path
        
        # 处理FastDFS路径 - 将group1/M00/路径映射到本地商品图片
        if path.startswith('/group1/M00/'):
            # 使用哈希方式将FastDFS路径映射到本地图片
            import hashlib
            path_hash = hashlib.md5(path.encode()).hexdigest()
            # 根据哈希值选择1-9中的一张图片
            image_num = (int(path_hash, 16) % 9) + 1
            local_image_path = os.path.join('meiduo_mall', 'static', 'images', 'goods', f'goods{image_num:03d}.jpg')
            
            if os.path.exists(local_image_path):
                try:
                    with open(local_image_path, 'rb') as f:
                        content = f.read()
                    
                    self.send_response(200)
                    self.send_header('Content-Type', 'image/jpeg')
                    self.send_header('Content-Length', str(len(content)))
                    self.end_headers()
                    self.wfile.write(content)
                    return
                except Exception as e:
                    print(f"Error serving FastDFS mapped image {local_image_path}: {e}")
                    self.send_error(500, "Internal server error")
                    return
            else:
                print(f"Mapped image not found: {local_image_path}")
                self.send_error(404, "Mapped image not found")
                return
        
        # 处理静态文件请求 - 将/static/路径映射到Django的static目录
        if path.startswith('/static/'):
            # 移除/static/前缀，映射到Django项目的static目录
            static_path = path[8:]  # 移除'/static/'
            django_static_path = os.path.join('meiduo_mall', 'static', static_path)
            
            if os.path.exists(django_static_path):
                # 读取文件并返回
                try:
                    with open(django_static_path, 'rb') as f:
                        content = f.read()
                    
                    # 设置正确的Content-Type
                    if django_static_path.endswith('.png'):
                        content_type = 'image/png'
                    elif django_static_path.endswith('.jpg') or django_static_path.endswith('.jpeg'):
                        content_type = 'image/jpeg'
                    elif django_static_path.endswith('.gif'):
                        content_type = 'image/gif'
                    elif django_static_path.endswith('.css'):
                        content_type = 'text/css'
                    elif django_static_path.endswith('.js'):
                        content_type = 'application/javascript'
                    else:
                        content_type = 'application/octet-stream'
                    
                    self.send_response(200)
                    self.send_header('Content-Type', content_type)
                    self.send_header('Content-Length', str(len(content)))
                    self.end_headers()
                    self.wfile.write(content)
                    return
                except Exception as e:
                    print(f"Error serving static file {django_static_path}: {e}")
                    self.send_error(500, "Internal server error")
                    return
            else:
                print(f"Static file not found: {django_static_path}")
                self.send_error(404, "Static file not found")
                return
        
        # 处理普通页面请求
        return super().do_GET()
    
    def end_headers(self):
        # 添加CORS头部以允许跨域请求
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        super().end_headers()

def main():
    PORT = 8080
    
    # 切换到项目根目录
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    
    print(f"当前工作目录: {os.getcwd()}")
    print(f"检查Django static目录: {os.path.exists('meiduo_mall/static')}")
    print(f"检查前端目录: {os.path.exists('front_end_pc')}")
    
    with socketserver.TCPServer(("", PORT), CustomHTTPRequestHandler) as httpd:
        print(f"前端服务器运行在 http://localhost:{PORT}")
        print(f"静态文件将从 Django static 目录提供服务")
        print("按 Ctrl+C 停止服务器")
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\n服务器已停止")

if __name__ == "__main__":
    main()